package com.lyn.solitude_plugin_host_ui.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import com.lyn.solitude_plugin_host_ui.R;
import com.lyn.solitude_plugin_host_ui.adapter.PluginAdapter;
import com.lyn.solitude_plugin_host_ui.databinding.FragmentPluginHostBinding;
import com.lyn.solitude_plugin_api.entity.Plugin;
import com.lyn.solitude_plugin_host.PluginHost;
import java.io.File;

/**
 * 插件宿主fragment
 * @author longyn 2024/05/11
 * @version 1.0.0
 */
public class PluginHostFragment extends Fragment {

    private final static String TAG = "PluginHostFragment";
    private final Handler handler = new Handler(Looper.getMainLooper());
    private FragmentPluginHostBinding binding;
    private final PluginAdapter pluginAdapter = new PluginAdapter();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentPluginHostBinding.inflate(inflater);
        initView();
        return binding.getRoot();
    }

    private void initView(){
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
        }
        pluginAdapter.setEmptyPluginListener(new PluginAdapter.EmptyPluginListener() {
            @Override
            public void onEmpty() {
                GridLayoutManager gridLayoutManager = (GridLayoutManager) binding.pluginRecycler.getLayoutManager();
                if (gridLayoutManager != null) {
                    gridLayoutManager.setSpanCount(1);
                }
            }

            @Override
            public void onNotEmpty() {
                GridLayoutManager gridLayoutManager = (GridLayoutManager) binding.pluginRecycler.getLayoutManager();
                if (gridLayoutManager != null) {
                    gridLayoutManager.setSpanCount(2);
                }
            }
        });
        binding.pluginRecycler.setAdapter(pluginAdapter);

        pluginAdapter.setOnItemClickListener((holder, position) -> {
            if (binding.swipeRefresh.isRefreshing()) {
                return;
            }
            Plugin.Simple simple = pluginAdapter.getItem(position);
            if (simple == null) {
                return;
            }
            PluginHost.open(simple.getId());
        });
        pluginAdapter.setOnItemLongClickListener((holder, position) -> {
            if (binding.swipeRefresh.isRefreshing()) {
                return true;
            }
            Plugin.Simple simple = pluginAdapter.getItem(position);
            if (simple == null) {
                return true;
            }
            new AlertDialog.Builder(requireContext())
                    .setTitle(getString(R.string.hint)).setMessage(getString(R.string.are_you_sure_you_want_to_uninstall_this_plugin))
                    .setNegativeButton(getString(R.string.cancel), (dialog, which) -> {
                        dialog.dismiss();
                    }).setPositiveButton(getString(R.string.confirm), (dialog, which) -> {
                        dialog.dismiss();
                        new Thread(() -> {
                            final int remove = PluginHost.remove(simple.getId());
                            handler.post(() -> {
                                if (remove == 0){
                                    Toast.makeText(requireContext(), getString(R.string.uninstall_successfully), Toast.LENGTH_SHORT).show();
                                }else {
                                    Toast.makeText(requireContext(), getString(R.string.uninstallation_failure), Toast.LENGTH_SHORT).show();
                                }
                            });

                        }).start();
                    }).setCancelable(false).show();
            return true;
        });
        binding.swipeRefresh.setOnRefreshListener(() -> {
            File externalFilesDir = requireContext().getExternalFilesDir("");
            File[] files = new File[0];
            if (externalFilesDir != null) {
                files = externalFilesDir.listFiles();
            }
            if (files != null) {
                for (File file : files) {
                    if (file.getName().endsWith(".apk")) {

                    }
                }
            }

            handler.postDelayed(() -> binding.swipeRefresh.setRefreshing(false), 1500);
        });

    }
}
